package com.xinzhidi.web.netty.utils;

import com.alibaba.fastjson2.JSONObject;
import com.xinzhidi.common.constant.AgreementConstants;
import com.xinzhidi.common.utils.StringUtils;
import com.xinzhidi.common.utils.spring.SpringUtils;
import com.xinzhidi.web.netty.entity.AgreementCommandField;
import com.xinzhidi.web.netty.entity.CommonField;
import com.xinzhidi.web.unitconversion.service.UnitConversionService;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * netty工具类
 *
 * @author cx
 */
@Component
public class NettyUtils {

    /**
     * 通用字段各字段长度 包含：起始符、设备类型、地址域
     */
    public static final List<Integer> CommonFieldLength = new ArrayList<>(Arrays.asList(1, 1, 7));

    /**
     * 通用字段类反射类包路径
     */
    public static final String PACKAGE_URL = "com.xinzhidi.web.netty.entity.CommonField";

    public static Integer CommonFieldByteLength;

    static {
        CommonFieldByteLength = CommonFieldLength.stream().reduce(Integer::sum).get();
    }

    /**
     * 获取通用字段，包含：起始符、设备类型、地址域
     *
     * @param message 消息体
     * @return 返回通用字段实体类
     **/
    public static CommonField getCommonField(String message) {
//        System.out.println("=========>>>>>得到的message为：" + message);
        CommonField commonField;
        message = message.replaceAll(HexadecimalUtil.PREFIX_UPPERCASE, "");
        message = message.replaceAll(HexadecimalUtil.PREFIX_LOWER, "");
        message = message.substring(0, CommonFieldByteLength * 2);
        JSONObject jsonObject = new JSONObject();
        try {
            Class<?> clazz = Class.forName(PACKAGE_URL);
            Field[] fields = clazz.getDeclaredFields();
            int start = 0, end;
            //十六进制value
            Object value;
            for (int i = 0; i < fields.length; i++) {
                end = start + CommonFieldLength.get(i) * 2;
                value = message.substring(start, end);
                start = end;
                jsonObject.put(fields[i].getName(), value);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        commonField = jsonObject.toJavaObject(CommonField.class);
        return commonField;
    }


    public static String bytes2hexFirst(byte[] bytes) {
        final String HEX = "0123456789abcdef";
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            // 取出这个字节的高4位，然后与0x0f与运算，得到一个0-15之间的数据，通过HEX.charAt(0-15)即为16进制数
            sb.append(HEX.charAt((b >> 4) & 0x0f));
            // 取出这个字节的低位，与0x0f与运算，得到一个0-15之间的数据，通过HEX.charAt(0-15)即为16进制数
            sb.append(HEX.charAt(b & 0x0f));
        }
        return sb.toString();
    }

    /**
     * 根据字节的开始位置和节数位置获取数字
     *
     * @param startNum        开始位置
     * @param endNum          结束位置
     * @param message         消息体
     * @param highLowPosition 高低位（0：是  1：否  默认：0）
     * @param coefficient     系数
     * @param hex             是否是十六进制（0：是  1：不是   默认0）
     * @return 返回校验码
     **/
    public static String getByteStr(Integer startNum, Integer endNum, String message, AgreementCommandField commandField) {

        message = message.toLowerCase();
        String newmessage = message.substring(0, 6);
        Integer times = StringUtils.containFrequency(newmessage, 'f');
        if (times < 3) {
            String feStr = "";
            for (int i = 0; i < (3 - times); i++) {
                feStr += "fe";
            }
            message = feStr + message;
        }


        String highLowPosition = commandField.getHighLowPosition();
        BigDecimal coefficient = commandField.getCoefficient();
        Integer hex = commandField.getHex();
        System.out.println("startNum为：" + startNum + "，endNum为：" + endNum);
        String str = message.substring(startNum * 2, endNum * 2);
        String code = "";
        if (commandField.getUnitFlag().equals("0")) {
            code = str.substring(0, 2);
            str = str.substring(2, str.length());
        }

        String value = "";
        if (highLowPosition.equals(AgreementConstants.IsHighLowPosition.ONE)) {
            value = HexadecimalUtil.convertToHighLow(str, hex);
            if (coefficient != null && coefficient.compareTo(new BigDecimal(1)) != 0) {
                value = new BigDecimal(value).multiply(coefficient).toString();
            }
        } else {
            value = str;
            if (hex == 0) {
                value = String.valueOf(FormatData.hex2decimal(str));
            }
            if (coefficient != null) {
                value = new BigDecimal(value).multiply(coefficient).toString();
            }
        }

        if (commandField.getUnitFlag().equals("0")) {
            UnitConversionService unitConversionService = SpringUtils.getBean(UnitConversionService.class);
            value = unitConversionService.unitConversion(value, code, hex);
        }

        return value;
    }

}
